<?php
require_once 'lib/phpQuery/phpQuery.php';

class Dom
{
	/**
	 * phpQuery representation of the base template.
	 *
	 * @var phpQuery
	 */
	static private $dom = null;
	
	/**
	 * Temporary home for tags that will be added later.
	 * 
	 * Sometimes other libraries will try to add tags before the document is
	 * loaded. In this case we should cache the tags and then run them after
	 * loading the template.
	 *
	 * @var array
	 */
	static private $tagCache = array();
	
	public static function initialize($templateName)
	{
		Event::log('framework.dom', 'Basing design on template '.$templateName);
		Event::dispatch('framework.dom.initialized');
		self::$dom = phpQuery::newDocumentFile(Config::get('path').$templateName);
		self::flushCache();
	}
	
	protected static function getDom()
	{
		return self::$dom;
	}
	
	public static function addTag($pos, $code)
	{
		if (self::$dom === null) {
			self::$tagCache[] = array($pos, $code);
			return;
		}
		
		$colonPos = strpos($pos, ':');
		if ($colonPos === false) {
			$instruction = 'html';
			$selectors = $pos;
		} else {
			$instruction = substr($pos, 0, $colonPos);
			$selectors = substr($pos, $colonPos+1);
		}
		
		$dom = self::getDom()
			->find($selectors);
		
		if (Config::get('debug')) {
			$numElements = $dom->length();
			Event::log('framework.dom', 'DOM edit "'.$pos.'" (matched '.$numElements.' elements)', array('code' => $code));
		}
			
		switch ($instruction) {
			case 'html':
				$dom->html($code);
				break;
			case 'replaceWith':
				$dom->replaceWith($code);
				break;
			case 'append':
			default:
				$dom->append($code);
		}
	}
	
	protected static function flushCache()
	{
		foreach (self::$tagCache as $tag) {
			self::addTag($tag[0], $tag[1]);
		}
	}
	
	public static function output()
	{
		Event::log('framework.dom', 'Outputting final template code');
		echo self::$dom;
	}
}
?>